package com.suse.service.community.controller;

import com.suse.common.config.response.R;
import com.suse.service.community.constant.EntityTypeConstant;
import com.suse.service.community.constant.TopicConstant;
import com.suse.service.community.kafka.Event;
import com.suse.service.community.kafka.EventProducer;
import com.suse.service.community.service.LikeService;
import com.suse.service.community.util.RedisUtil;
import com.suse.service.community.util.UserHolder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * <p>
 * 点赞前端控制器
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-09-02 14:00
 */
@Controller
public class LikeController {

    @Resource
    private LikeService likeService;

    @Resource
    private EventProducer eventProducer;

    @Resource
    private RedisTemplate<Object,Object> redisTemplate;

    @GetMapping("/like")
    @ResponseBody
    public R like(int entityType, int entityId, int entityUserId, int postId) {
        // 点赞
        likeService.like(entityType, entityId, entityUserId);
        // 点赞数
        long likeCount = likeService.getEntityLikeCount(entityType, entityId);
        // 点赞状态
        int likeStatus = likeService.getEntityLikeStatus(entityType, entityId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("likeCount",likeCount);
        map.put("likeStatus",likeStatus);
        // 触发点赞事件
        Integer userId = UserHolder.getUser().getId();
        if (likeStatus == 1) {
            Event event = new Event();
            event.setTopic(TopicConstant.LIKE);
            event.put("userId",userId);
            event.put("entityType",entityType);
            event.put("entityId",entityId);
            event.put("postId",postId);
            event.put("entityUserId",entityUserId);
            eventProducer.fireEvent(event);
        }
        if (entityType == EntityTypeConstant.POST) {
            // 将帖子ID放入Redis的待刷新集合中 无序不重复集合
            redisTemplate.opsForSet().add(RedisUtil.getNeedRefreshScorePostsKey(),postId);
        }
        return R.success(map);
    }

}
